const {
	config,
	updateConfig
} = require('./config.js'); // 引入配置文件
const base64 = require('./base64.js'); // Base64, hmac, sha1, crypto相关算法
require('./hmac.js');
require('./sha1.js');
const Crypto = require('./crypto.js');

import {
	getOssSecretKey
} from '@/api/user.js';

/*
 * 上传文件到阿里云oss
 * @param - filePath : 图片的本地资源路径
 * @param - dir: 表示要传到哪个目录下
 * @param - successc: 成功回调
 * @param - failc: 失败回调
 */
const uploadFile = async function(filePath, dir, successc = () => {}, failc = (err) => console.error(err)) {
	// console.log('Parameters:', { filePath, dir, successc, failc }); // 输出参数，检查它们的类型

	if (!filePath || filePath.length < 9) {
		uni.showModal({
			title: '图片错误',
			content: '请重试',
			showCancel: false,
		});
		return;
	}

	try {
		const res = await getOssSecretKey();
		const {
			accessKeyId,
			accessKeySecret,
			securityToken,
			expiration
		} = res.data;

		// 更新配置对象
		updateConfig({
			AccessKeySecret: accessKeySecret,
			OSSAccessKeyId: accessKeyId,
			SecurityToken: securityToken,
			expiration: expiration
		});

		// 图片名字 可以自行定义，这里是采用当前的时间戳 + 150内的随机数来给图片命名的
		const aliyunFileKey = dir + new Date().getTime() + Math.floor(Math.random() * 150) + '.png';
		const aliyunServerURL = 'https://beauty-of-face.oss-cn-shanghai.aliyuncs.com/'; // OSS地址，需要https
		const accessid = config.OSSAccessKeyId;
		const policyBase64 = getPolicyBase64();
		const signature = getSignature(policyBase64); // 获取签名

		// console.log(aliyunServerURL, "aliyunServerURL");
		// console.log(filePath, "filePath");
		// console.log(aliyunFileKey, "key");
		// console.log(policyBase64, "policy");
		// console.log(accessid, "OSSAccessKeyId");
		// console.log(signature, "signature");
		// console.log(config.SecurityToken, "x-oss-security-token");

		uni.uploadFile({
			url: aliyunServerURL, // 开发者服务器 url
			filePath: filePath, // 要上传文件资源的路径
			name: 'file', // 必须填file
			formData: {
				'key': aliyunFileKey,
				'policy': policyBase64,
				'OSSAccessKeyId': accessid,
				'signature': signature,
				'success_action_status': '200',
				'x-oss-security-token': config.SecurityToken // 添加 SecurityToken
			},
			success: function(res) {
				// console.log(res, "上传了");
				if (res.statusCode != 200) {
					failc(new Error('上传错误:' + JSON.stringify(res)));
					return;
				}
				successc(aliyunServerURL + aliyunFileKey);
			},
			fail: function(err) {
				err.wxaddinfo = aliyunServerURL;
				failc(err);
			},
		});
	} catch (error) {
		// console.error('加载配置失败:', error);
		failc(error);
	}
};

const getPolicyBase64 = function() {
	let date = new Date();
	date.setHours(date.getHours() + config.timeout);
	let srcT = date.toISOString();
	const policyText = {
		"expiration": srcT, // 设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
		"conditions": [
			["content-length-range", 0, 5 * 1024 * 1024] // 设置上传文件的大小限制,5mb
		]
	};

	const policyBase64 = base64.encode(JSON.stringify(policyText));
	console.log(policyBase64);
	return policyBase64;
};

const getSignature = function(policyBase64) {
	const accesskey = config.AccessKeySecret;

	const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
		asBytes: true
	});
	const signature = Crypto.util.bytesToBase64(bytes);
	console.log(signature);
	return signature;
};

module.exports = uploadFile;